package com.lzs.bootsafety.common.oss;

import com.alibaba.fastjson.JSON;
import com.lzs.bootsafety.business.oss.entity.SysFile;
import com.lzs.bootsafety.common.oss.Exception.OssException;
import com.lzs.bootsafety.common.util.oss.FileUtils;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.StringUtils;

import java.io.*;
import java.net.*;
import java.util.Date;
/**
 *  @author  zhanshi Liu
 *  @date    2020/04/20
 *  @website www.jhmsona.cn
 *
 */
public class QiniuApi extends BaseApi{
    private String accessKey;
    private String secretKey;
    private String bucket;
    private String path;
    private String qiniuStoragePath;
    private Configuration cf;
    private UploadManager uploadManager;
    private Auth auth;

    QiniuApi() {
        super("七牛云");
    }
    public QiniuApi init(String accessKey,String secretKey,String bucket,String fileUrl,String qiniuStoragePath){
        this.accessKey=accessKey;
        this.secretKey=secretKey;
        this.bucket=bucket;
        this.path=fileUrl;//cdn加速域名
        this.qiniuStoragePath = qiniuStoragePath;
        cf = new Configuration(Region.autoRegion());
        uploadManager = new UploadManager(cf);
        auth = Auth.create(this.accessKey,this.secretKey);
        return this;
    }

    @Override
    public SysFile uploadFile(InputStream is, String fileUrl) {
        Date date = new Date();
        this.check();
        String key = FileUtils.generateTempFileName(fileUrl);
        this.createNewName(fileUrl);
        String token = auth.uploadToken(this.bucket);
        try {
            Response res = uploadManager.put(is,this.qiniuStoragePath+this.newFileName,token,null,null);
            DefaultPutRet putRet = JSON.parseObject(res.bodyString(),DefaultPutRet.class);
            return new SysFile().setOriginalFileName(key).setSuffix(this.suffix)
                .setUploadStartTime(date).setUploadEndTime(new Date())
                .setFileHash(putRet.hash).setFilePath(putRet.key)
                .setFullFilePath(this.path+this.qiniuStoragePath+putRet.key);
        } catch (QiniuException e) {
            e.printStackTrace();
            throw new OssException(this.storageType+"文件上传失败:"+e.error());
        }
    }

    @Override
    public boolean download(String fileName) {
        check();
        try {
            String encodeFileName = URLEncoder.encode(fileName, "utf-8").replace("+", "%20");
            String publicUrl = String.format("%s%s",this.path,encodeFileName);
            String finalUrl = URLDecoder.decode(publicUrl, "UTF-8");
            URL url = new URL(finalUrl);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            InputStream is = conn.getInputStream();
            FileUtils.downloadFile(fileName,is,storageType);
            return true;
        } catch (IOException e) {
            throw new OssException("["+this.storageType+"]IO异常下载失败:"+e.getMessage());
        }

    }

    @Override
    public boolean delete(String filePath) {
        check();
        try {
            BucketManager bucketManager = new BucketManager(auth,cf);
            return bucketManager.delete(bucket,filePath).isOK();
        } catch (QiniuException e) {
            Response res = e.response;
            throw new OssException("[" + this.storageType + "]删除文件发生异常：" + res.toString());
        }
    }

    /*检查配置是否可用*/
    public void check(){
        if (StringUtils.isNullOrEmpty(this.accessKey) || StringUtils.isNullOrEmpty(this.secretKey) || StringUtils.isNullOrEmpty(this.bucket)) {
            throw new OssException("[" + this.storageType + "]尚未配置七牛云，文件上传功能暂时不可用！");
        }
    }
}
